package com.tg.app.view;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.Configuration;
import android.graphics.drawable.Drawable;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.DrawableRes;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.magicindicator.buildins.UIUtil;
import com.tg.app.R;
import com.tg.app.activity.device.CameraViewActivity;
import com.tange.module.device.feature.DeviceFeature;
import com.tg.app.helper.DeviceUIHelper;
import com.tange.base.toolkit.AppUtil;
import com.tange.base.toolkit.DateUtil;
import com.tg.appcommon.android.LanguageUtils;
import com.tg.appcommon.android.ResourcesUtil;
import com.tange.base.toolkit.StringUtils;
import com.tg.appcommon.android.TGApplicationBase;
import com.tg.appcommon.android.TGLog;

public class CameraPlayerToolbarView extends LinearLayout implements View.OnClickListener {
    private static final String TAG = "CameraPlayerToolbarView";
    public static final String SPEED_1 = "1";
    public static final String SPEED_2 = "2";
    public static final String SPEED_4 = "4";
    public static final String SPEED_8 = "8";
    private ImageButton btnMute, btnResolution, btnFullScreen, btnScreenShot, btnScreenCap, btnControl, banMicrophone;
    private ImageButton speedText;
    private TextView timelineText;
    private ImageView timelineIv;
    private CameraPlayerToolbarViewClickListener toolbarViewClickListener;
    private View controlToolbarLayout;
    private LinearLayout timeLineLayout;
    private DeviceUIHelper mDeviceUIHelper;
    private DeviceFeature deviceFeature;

    public void setToolbarViewClickListener(CameraPlayerToolbarViewClickListener toolbarViewClickListener) {
        this.toolbarViewClickListener = toolbarViewClickListener;
    }

    public void setDeviceUIHelper(DeviceUIHelper mDeviceUIHelper) {
        this.mDeviceUIHelper = mDeviceUIHelper;
    }

    public CameraPlayerToolbarView(Context context) {
        super(context);
        initView(context);
    }

    public CameraPlayerToolbarView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        initView(context);

    }

    public CameraPlayerToolbarView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initView(context);
    }

    public void showMute(boolean show){
        btnMute.setVisibility(show? VISIBLE : GONE);
    }
    public void showLockDellImageIcon(){
        btnMute.setVisibility(VISIBLE);
        btnScreenCap.setVisibility(VISIBLE);
        btnScreenShot.setVisibility(VISIBLE);
        btnResolution.setVisibility(GONE);
        btnFullScreen.setVisibility(GONE);
        btnControl.setVisibility(GONE);
        banMicrophone.setVisibility(GONE);
        speedText.setVisibility(GONE);
        controlToolbarLayout.setVisibility(GONE);
        timeLineLayout.setVisibility(GONE);
        timelineText.setVisibility(GONE);
        timelineIv.setVisibility(GONE);
    }

    private void initView(Context context) {
        View view = LayoutInflater.from(context).inflate(R.layout.layout_camera_player_toolbar_view, this);
        btnMute = view.findViewById(R.id.btn_camera_player_mute);
        btnResolution = view.findViewById(R.id.btn_camera_player_resolution);
        btnFullScreen = view.findViewById(R.id.btn_camera_player_screen);
        btnScreenShot = view.findViewById(R.id.btn_camera_player_screenshot);
        btnScreenCap = view.findViewById(R.id.btn_camera_player_screencap);
        btnControl = view.findViewById(R.id.btn_camera_player_control);
        banMicrophone = view.findViewById(R.id.btn_camera_player_micphone);
        speedText = view.findViewById(R.id.btn_camera_player_speed);
        controlToolbarLayout = view.findViewById(R.id.ll_camera_player_control_toolbar);
        timeLineLayout = view.findViewById(R.id.ll_camera_player_timeline);
        timelineText = view.findViewById(R.id.tv_camera_player_timeline);
        timelineIv = view.findViewById(R.id.ll_camera_player_timeline_iv);
        setClickListener();


        /**
         * 小屏幕适配原则：
         *
         * 竖屏的时候，是最多6个按钮，加一些间距
         * 声音 btnMute
         * 录屏 btnScreenCap
         * 截图 btnScreenShot
         * 标清 btnResolution
         * 云台 btnControl
         * 横屏 btnFullScreen
         *
         * 每个按钮宽度是50dp，间距每个10DP，一共7个
         *
         * 这里需要动态计算，如果6个按钮加上间距，已经超出屏幕的DP了，那么，就重新计算出一个合适的DP给按钮
         */
        final int screenWidthDP = UIUtil.getScreenWidthDp(getContext());
        final int targetMinWidthDp = 6 * 50 + 7 * 10;
        final int targetButtonWidth = UIUtil.dip2px(getContext(), 50);
        Log.i(TAG, "initView: screenWidthDP = " + screenWidthDP);
        Log.i(TAG, "initView: targetMinWidthDp = " + targetMinWidthDp);
        Log.i(TAG, "initView: targetButtonWidth = " + targetButtonWidth);
        if (screenWidthDP < targetMinWidthDp) {
            final int newWidthDP = (screenWidthDP - 7 * 10) / 6; // 间距不变，按钮的尺寸变小点
            final int newWidth = UIUtil.dip2px(getContext(), newWidthDP);
            Log.i(TAG, "initView: need to resize, newWidthDP = " + newWidthDP);
            updateButtonSize(btnMute, newWidth);
            updateButtonSize(btnScreenCap, newWidth);
            updateButtonSize(btnScreenShot, newWidth);
            updateButtonSize(btnResolution, newWidth);
            updateButtonSize(btnControl, newWidth);
            updateButtonSize(btnFullScreen, newWidth);
            // 其他的按钮大小也要跟着变，否则大小不一
            updateButtonSize(timelineIv, newWidth);
            updateButtonSize(speedText, newWidth);
            updateButtonSize(banMicrophone, newWidth);
        } else {
            Log.i(TAG, "initView: no need to resize");

        }
    }

    private void updateButtonSize(View button, int newSize) {
        if (button.getLayoutParams() instanceof ViewGroup.LayoutParams) {
            ViewGroup.LayoutParams lp = (ViewGroup.LayoutParams) button.getLayoutParams();
            lp.width = newSize;
            lp.height = newSize;
            button.setLayoutParams(lp);
        }
    }

    private void setClickListener() {
        btnMute.setOnClickListener(this);
        btnResolution.setOnClickListener(this);
        btnFullScreen.setOnClickListener(this);
        btnScreenShot.setOnClickListener(this);
        btnScreenCap.setOnClickListener(this);
        btnControl.setOnClickListener(this);
        banMicrophone.setOnClickListener(this);
        speedText.setOnClickListener(this);
        timeLineLayout.setOnClickListener(this);
    }

    public void animateShow() {
        this.animate().translationY(0).alpha(1.0f).setDuration(240).setListener(null).start();
        setVisibility(View.VISIBLE);
    }

    public void setScreenCapEnable(){
        btnScreenCap.setEnabled(true);
        btnScreenCap.setAlpha(1.0f);
    }
    public void setScreenCapDisable(){
        btnScreenCap.setEnabled(false);
        btnScreenCap.setAlpha(0.4f);
    }
    public void animateHide() {
        int h = getHeight();
        animate().translationY(h).setDuration(240).setListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                super.onAnimationEnd(animation);
                setVisibility(View.GONE);
            }
        }).start();
    }

    public void setResolutionVisibility(boolean visible) {
        btnResolution.setVisibility(visible ? VISIBLE : GONE);
    }

    public void setSpeedVisibility(boolean visible) {
        speedText.setVisibility(visible ? VISIBLE : GONE);

    }

    public void setDateLine(String dateLine) {
        String md = DateUtil.getFormatMd(dateLine);
        timelineText.setText(md);
        if (TextUtils.equals(dateLine, DateUtil.getTodayDate())) {
            if (LanguageUtils.isSimChinese(getContext())){
                timelineText.setText(R.string.date_today_record);
            }
        }
    }

    public void onOrientationChanged(int o, boolean isShowPlayback) {
        if (o == Configuration.ORIENTATION_PORTRAIT) {
            timeLineLayout.setVisibility(GONE);
        } else {
            timeLineLayout.setVisibility(isShowPlayback && AppUtil.isLandscape(TGApplicationBase.getApplicationContext()) ? VISIBLE : GONE);
        }
    }

    public String getSpeedDescription() {
        return speedText.getContentDescription().toString();
    }

    public void setSpeedIcon(String text) {
        if (!StringUtils.isEmpty(text)) {
            @SuppressLint("ResourceType") @DrawableRes int resId = R.mipmap.icon_camera_playback_speed_left;
            String speed = text.replace("X", "");
            switch (speed) {
                case SPEED_2:
                    resId = R.mipmap.icon_camera_playback_speed_left2;
                    break;
                case SPEED_4:
                    resId = R.mipmap.icon_camera_playback_speed_left4;
                    break;
                case SPEED_8:
                    resId = R.mipmap.icon_camera_playback_speed_left8;
                    break;
            }
            Drawable drawable = ResourcesUtil.getDrawable(resId);
            speedText.setImageDrawable(drawable);
            speedText.setContentDescription(text);
        }
    }

    public void screenSaveEnd() {
        btnScreenCap.setClickable(true);
        btnScreenShot.setClickable(true);
        btnResolution.setClickable(true);
    }

    public void supportPTZ() {
        btnControl.setVisibility(VISIBLE);
    }
    
    public void hidePTZ(){
        btnControl.setVisibility(GONE);
    }


    public void supportSpeaker() {
        banMicrophone.setVisibility(VISIBLE);
    }

    public void setPlayback(boolean isPlayback) {
        if (isPlayback) {
            btnControl.setVisibility(GONE);
            banMicrophone.setVisibility(GONE);
        }
    }

    public void setResolutionImageResource(int resId) {
        btnResolution.setImageResource(resId);
    }

    public void seMute(boolean muteOn) {
        btnMute.setImageResource(muteOn? R.drawable.ic_tange_global_icon_mute_on_white : R.drawable.ic_tange_global_icon_mute_off_white);
    }
    public void setMuteEnable(boolean enable){
        btnMute.setEnabled(enable);
        btnMute.setClickable(enable);
    }



    @Override
    protected void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        TGLog.d(TAG, "onConfigurationChanged");

        if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) {
            btnFullScreen.setVisibility(VISIBLE);
            banMicrophone.setVisibility(GONE);
            RelativeLayout.LayoutParams centerToolbarParams = (RelativeLayout.LayoutParams) controlToolbarLayout.getLayoutParams();
            centerToolbarParams.removeRule(RelativeLayout.ALIGN_PARENT_END);
            centerToolbarParams.removeRule(RelativeLayout.START_OF);
            centerToolbarParams.addRule(RelativeLayout.END_OF, R.id.ll_camera_player_left);
            controlToolbarLayout.setLayoutParams(centerToolbarParams);

        } else {
            btnFullScreen.setVisibility(GONE);
            RelativeLayout.LayoutParams centerToolbarParams = (RelativeLayout.LayoutParams) controlToolbarLayout.getLayoutParams();
            centerToolbarParams.removeRule(RelativeLayout.END_OF);
            centerToolbarParams.addRule(RelativeLayout.START_OF, R.id.ll_camera_player_timeline);
            if (mDeviceUIHelper != null && mDeviceUIHelper.getPlaybackDisplay() == CameraViewActivity.PLAY_MODE_REALTIME){
                centerToolbarParams.removeRule(RelativeLayout.START_OF);
                centerToolbarParams.addRule(RelativeLayout.ALIGN_PARENT_END);
            }
            controlToolbarLayout.setLayoutParams(centerToolbarParams);

        }

    }

    @Override
    public void onClick(View v) {
        if (toolbarViewClickListener == null) return;
        int viewId = v.getId();
        if (viewId == R.id.btn_camera_player_mute) {
            toolbarViewClickListener.onMuteOnClick();
        } else if (viewId == R.id.btn_camera_player_micphone) {
            toolbarViewClickListener.onMicphoneLandClick();
        } else if (viewId == R.id.btn_camera_player_screencap) {
            toolbarViewClickListener.onScreenCapClick();
        } else if (viewId == R.id.btn_camera_player_screen) {
            toolbarViewClickListener.onScreenFullClick();
        } else if (viewId == R.id.btn_camera_player_screenshot) {
            toolbarViewClickListener.onScreenShotResult();
        } else if (viewId == R.id.btn_camera_player_resolution) {
            toolbarViewClickListener.onResolutionChanged(v);
        } else if (viewId == R.id.btn_camera_player_speed) {
            toolbarViewClickListener.onSpeedClick(v);
        } else if (viewId == R.id.btn_camera_player_control) {
            toolbarViewClickListener.onPtzControlClick();
        } else if (viewId == R.id.ll_camera_player_timeline) {
            toolbarViewClickListener.onPlayBackControlClick();
        }
    }

    public void setDeviceFeature(@NonNull DeviceFeature deviceFeature) {
        this.deviceFeature = deviceFeature;
    }

    public interface CameraPlayerToolbarViewClickListener {
        void onMuteOnClick();

        void onSpeedClick(View view);

        void onResolutionChanged(View view);

        void onScreenShotResult();

        void onScreenFullClick();

        void onMicphoneLandClick();

        void onScreenCapClick();

        void onPtzControlClick();

        void onPlayBackControlClick();
    }
}
